<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="listQuery.gid" placeholder="订单号" style="width: 250px;" class="filter-item" @keyup.enter.native="searchList" />
      <el-input v-model="listQuery.phone" placeholder="手机号" style="width: 250px;" class="filter-item" @keyup.enter.native="searchList" />
      <el-select v-model="listQuery.state" placeholder="订单状态" clearable class="filter-item" style="width: 150px">
        <el-option v-for="item in stateOptions" :key="item.index" :label="item.value" :value="item.index" />
      </el-select>
      <el-date-picker
        v-model="date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="filter-item"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="searchList">
        搜索
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="订单号" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="金额" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.totalPrice || '暂无' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" width="130px" align="center">
        <template slot-scope="{row}">
          <el-tag>{{ row.state | typeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物流公司" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.courier }}</span>
        </template>
      </el-table-column>
      <el-table-column label="快递单号" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.courierNo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.payTime || '暂无' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="edit(row)">
            编辑
          </el-button>
          <el-button v-if="row.state!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :limit.sync="listQuery.pageSize"
      :page.sync="listQuery.pageIndex"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="域名" prop="domain">
          <el-input v-model="temp.domain" readonly />
          <!-- <el-select v-model="temp.domain" class="filter-item" placeholder="Please select">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="temp.realName" readonly />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" readonly />
        </el-form-item>
        <el-form-item label="手机号" prop="telphone">
          <el-input v-model="temp.telphone" readonly />
        </el-form-item>
        <el-form-item label="订单ID" prop="orderID">
          <el-input v-model="temp.orderID" readonly />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="state" class="filter-item" placeholder="请选择">
            <el-option v-for="item in stateOptions" :key="item.index" :label="item.value" :value="item.index" />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateOrderDetail()">
          确认
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getOrderInfo, getOrders, updateDeliverWare } from '@/api/orders'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

import { renderTime } from '@/utils/util'
import { phoneReg, mailReg } from '@/utils/validate.js'

// 总订单状态：0 订单处理中 1 订单完成 -1 订单支付失败 2订单已确认 3银行转账待确认
// 域名子订单 ：1待审核 2 审核通过 3 订单上传完成 -1 审核失败 0初始化
// const stateOptions = [
//   { index: 0, value: '订单处理中' },
//   { index: 1, value: '订单完成' },
//   { index: -1, value: '订单支付失败' },
//   { index: 2, value: '订单已确认' },
//   { index: 3, value: '银行转账待确认' }
// ]
const stateOptions = [
  { index: 100, value: '已完成' },
  { index: 101, value: '待付款' },
  { index: 102, value: '待处理' },
  { index: 103, value: '待收货' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = stateOptions.reduce((acc, cur) => {
  acc[cur.index] = cur.value
  return acc
}, {})

export default {
  name: 'Orders',
  components: { Pagination },
  directives: { waves },
  filters: {
    typeFilter(index) {
      return calendarTypeKeyValue[index]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        gid: '',
        phone: '',
        state: '',
        pageIndex: 1,
        pageSize: 10,
        startTime: '',
        endTime: ''
      },
      date: '',
      stateOptions,
      sord: '-id',
      state: '',
      temp: {
        orderId: '',
        domain: '',
        realName: '',
        email: '',
        telphone: '',
        state: '',
        errorMsg: ''
      },
      rules: {
        email: [{ pattern: mailReg, message: '请输入正确邮箱', trigger: 'blur' }],
        telphone: [{ pattern: phoneReg, message: '请输入正确邮箱', trigger: 'blur' }]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: 'Create'
      }
    }
  },
  watch: {
    date: {
      handler: function(newV) {
        if (newV && newV.length === 2) {
          this.listQuery.startTime = this.renderTime(newV[0], '{y}-{m}-{d}')
          this.listQuery.endTime = this.renderTime(newV[1] + 86400000, '{y}-{m}-{d}')
        } else if (newV && newV.length !== 2) {
          this.$message({
            type: 'error',
            message: '日期选择出错'
          })
        } else {
          this.listQuery.startTime = ''
          this.listQuery.endTime = ''
        }
      }
    },
    state: {
      handler(newV) {
        if (typeof (newV) === 'number') {
          this.temp.state = newV
        }
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    renderTime,
    // 1：域名 2：邮箱 3：网站4：安全
    getList() {
      this.listLoading = true
      getOrders(this.listQuery).then(response => {
        console.log(response)
        this.list = response.result.list
        this.total = response.result.total
      })
      this.listLoading = false
    },
    searchList() {
      this.listQuery.pageIndex = 1
      this.getList()
    },
    edit(row) {
      this.temp.orderId = row.orderId
      this.temp.domain = row.domain
      this.temp.realName = row.realName
      this.temp.email = row.email
      this.temp.telphone = row.telphone
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.stateOptions.forEach(item => {
        if (item.index === row.state) {
          this.state = item.value
          this.temp.state = row.state
        }
      })
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新表格内容
    updateOrderDetail() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateOrderDetail({ orderId: this.temp.orderId, state: this.temp.state, errorMsg: this.temp.errorMsg }).then(() => {
            this.$notify({
              title: '成功',
              message: '订单更新成功~',
              type: 'success',
              duration: 2000
            })
            this.dialogFormVisible = false
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    }
  }
}
</script>
<style lang="scss">
    @import '@/assets/scss/mixin.scss';
    .el-form-item--medium{
      .el-form-item__content{
        display: flex;
        align-items: center;
        .el-input{
          &+.el-button{
            margin-left: 0.625rem;
          }
        }
        .el-button{
          &:not(:first-child){
            margin-left: 0.625rem;
          }
        }
      }
    }
</style>
